/*
* 获取本地JSON文件内容
* urlPath: 文件路径
* return: JSON字符串
* */
export const GetJsonWithFile = (urlPath: string) => {
  return new Promise(resolve => {
    fetch(urlPath).then((response) => response.json()).then((json) => {
      resolve(json)
    })
  })
}

/*
* 获取本地图片路径
* name: 图片名称
* */
export const GetImageUrl = (name: string) => {
  return new URL(`@/assets/images/${name}`, import.meta.url).href
}

/*
* 获取对象树的对象路径
* data: 数据源 例: ( [{id: 1, name: 'a', children:[{id: 2, name: 'b', children: []}] )
* key: 目标key
* name: 对象key名，默认id
* list: 路径集合
* return: 路径对象集合 例: ( [{id: 1}, {id:２}] )
* */
export const getPath = (data: any[], key: string, name: string = 'id', list: any[] = []): any[] | undefined => {
  for (const item of data) {
    const arr: any[] = [...list, item]
    if (item[name] === key) return arr
    if (item.children && item.children.length) {
      const result: any = getPath(item.children, key, name, arr)
      if (result) return result
    }
  }
}

export const GetAllValueWithKey = (data: any[], key: string = 'id', list: string[] = []) => {
  data.forEach(item => {
    if (item.children && item.children.length) {
      list.push(item[key])
      GetAllValueWithKey(item.children, key, list)
    }
  })
  return list
}

/*
* 搜索树对象关键字
* @param treeList 树列表
* @param value 关键字
* @param search 搜索字段
* */
export const FilterTreeWithName = (treeList: any[], value: string = '', search: string[] = ['name']): any[] => {
  const result = []
  for (const item of treeList) {
    if (search.some(v => item[v].indexOf(value) > -1)) {
      result.push(item)
    } else {
      if (item.children && item.children.length) {
        const temp = FilterTreeWithName(item.children, value, search)
        if (temp.length) {
          result.push({
            ...item,
            children: temp
          })
        }
      }
    }
  }
  return result
}